<template>
  <div>
    <!-- 文件上传部分 -->
    <h2>快照上传</h2>
    <input type="file" @change="handleFileSelect" />
    <button @click="uploadFile">上传文件</button>
    <p v-if="uploadStatus">{{ uploadStatus }}</p>
    <!-- 预览区域 -->
    <div v-if="previewUrl">
      <h2>文件预览</h2>
      <template v-if="isImage">
        <img :src="previewUrl" alt="Preview" style="max-width: 100%;" />
      </template>
      <template v-if="isVideo">
        <video :src="previewUrl" controls style="max-width: 100%;"></video>
      </template>
      <template v-if="isExcel">
        <p>暂不支持直接预览 Excel 文件，请下载查看。</p>
      </template>
    </div>
    <!-- 文件下载部分 -->
    <a :href="getDownloadUrl()" download>下载文件</a>
    <p v-if="downloadStatus">{{ downloadStatus }}</p>
    <p/>
    <!-- 摄像头视频显示区域 -->
    <video ref="videoElement" width="320" height="240" autoplay v-if="isCapturing"></video>
    <canvas ref="canvasElement" width="320" height="240" v-if="isCapturing"></canvas>
    <button v-if="!isCapturing" @click="startCapture">开启摄像头</button>
    <button v-if="isCapturing" @click="stopCapture">停止捕获</button>
    <button v-if="isCapturing" @click="takeSnapshot">截取图片</button>
  </div>
</template>

<script setup>
import { ref, defineProps } from 'vue';
import axios from 'axios';

// 接收父组件传递的数据
const props = defineProps({
  data: {
    type: Object,
    required: true
  }
});

const formData = ref({...props.data });
const selectedFile = ref(null);
const uploadStatus = ref('');
const downloadStatus = ref('');
const previewUrl = ref('');
const isImage = ref(false);
const isVideo = ref(false);
const isExcel = ref(false);
const isCapturing = ref(false);
const videoElement = ref(null);
const canvasElement = ref(null);
const mediaStream = ref(null);
const mediaRecorder = ref(null);
const recordedChunks = ref([]);

// 处理文件选择事件的方法
const handleFileSelect = (event) => {
  selectedFile.value = event.target.files[0];
  if (selectedFile.value) {
    const fileType = selectedFile.value.type;
    isImage.value = fileType.startsWith('image/');
    isVideo.value = fileType.startsWith('video/');
    isExcel.value = [
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ].includes(fileType);
    previewUrl.value = URL.createObjectURL(selectedFile.value);
  }
};

// 上传文件的方法
const uploadFile = async () => {
  if (!selectedFile.value) {
    uploadStatus.value = '请选择一个文件';
    return;
  }
  const uploadFormData = new FormData();
  uploadFormData.append('file', selectedFile.value);
  uploadFormData.append('userId', formData.value.id);
  uploadFormData.append('pileId', formData.value.pileNumber);
  try {
    uploadStatus.value = '正在上传...';
    const response = await axios.post('http://192.168.1.245:8081/file/upload', uploadFormData, {
      headers: {
        'Content-Type':'multipart/form-data'
      }
    });
    if (response.status === 200) {
      uploadStatus.value = '文件上传成功';
    } else {
      uploadStatus.value = `文件上传失败: 服务器返回状态码 ${response.status}`;
    }
  } catch (error) {
    if (error.request) {
      uploadStatus.value = '文件上传失败: 网络连接错误';
    } else if (error.response) {
      uploadStatus.value = `文件上传失败: 服务器返回状态码 ${error.response.status}，错误信息: ${error.response.data.message}`;
    } else {
      uploadStatus.value = `文件上传失败: ${error.message}`;
    }
  }
};

// 生成包含参数的下载 URL
const getDownloadUrl = () => {
  const baseUrl = 'http://192.168.1.245:8081/file/download';
  return `${baseUrl}?userId=${formData.id}&pileId=${formData.pileNumber}`;
};

// 开启摄像头
const startCapture = async () => {
  try {
    mediaStream.value = await navigator.mediaDevices.getUserMedia({ video: true });
    videoElement.value.srcObject = mediaStream.value;
    isCapturing.value = true;
    mediaRecorder.value = new MediaRecorder(mediaStream.value);
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data);
      }
    };
    mediaRecorder.value.start();
  } catch (error) {
    console.error('无法开启摄像头:', error);
  }
};

// 停止捕获
const stopCapture = () => {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop();
  }
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach(track => track.stop());
    isCapturing.value = false;
  }
};

// 截取图片
const takeSnapshot = () => {
  if (isCapturing.value && videoElement.value && canvasElement.value) {
    const ctx = canvasElement.value.getContext('2d');
    ctx.drawImage(videoElement.value, 0, 0, canvasElement.value.width, canvasElement.value.height);
    const dataURL = canvasElement.value.toDataURL('image/png');
    // 这里可以添加将截图上传或保存的逻辑
    console.log('截图完成，图片 URL:', dataURL);
  }
};
</script>

<style scoped>
h2 {
  margin-top: 20px;
}
button {
  margin-top: 10px;
}
label {
  display: block;
  margin-top: 10px;
}
input[type="text"] {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  box-sizing: border-box;
}
ul{
  list-style-type: none;
  display: flex;
}
</style>